package com.meizu.asum.richtextsdk.tools;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Description： 下载管工具<br>
 * User：Xie JunWen <br>
 * Email：v-xiejunwen@meizu.com <br>
 * CreateTime：2018/1/18  14:25 <br>
 * Remark：无
 */
public class DownloadTools {
    private Context context;
    private Map<String, SimpleTarget> targetMap;
    private ArrayList<SimpleTarget> targets;

    public DownloadTools(Context context) {
        this.context = context;
        targetMap = new HashMap<>();
        targets = new ArrayList<>();
    }

    public void download(int insertStart, int insertEnd, SpannableString spannableString, String picUrl, DownloadToolsCallBack callBack) {
        SimpleTarget target = Glide.with(context).load(picUrl).downloadOnly(new DownloadToolsTarget(insertStart, insertEnd, spannableString, callBack));
        targetMap.put(insertStart + "-" + insertEnd, target);
        Log.i("XJW", "添加任务：" + target);
    }

    public void clear() {
        for (SimpleTarget target : targets) {
            Glide.clear(target);
        }
    }

    public interface DownloadToolsCallBack {
        void begin();

        void success(int insertStart, int insertEnd, SpannableString spannableString, String filePath);

        void fail();
    }

    public class DownloadToolsTarget extends SimpleTarget<File> {
        private int insertStart, insertEnd;
        private SpannableString spannableString;
        private DownloadToolsCallBack callBack;

        public DownloadToolsTarget(int insertStart, int insertEnd, SpannableString spannableString, DownloadToolsCallBack callBack) {
            this.insertStart = insertStart;
            this.insertEnd = insertEnd;
            this.spannableString = spannableString;
            this.callBack = callBack;
        }

        @Override
        public void onStart() {
            if (callBack != null) {
                callBack.begin();
            }
        }

        @Override
        public void onLoadFailed(Exception e, Drawable errorDrawable) {
            if (callBack != null) {
                callBack.fail();
            }
        }

        @Override
        public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
            if (callBack != null) {
                callBack.success(insertStart, insertEnd, spannableString, resource.getPath());
            }
        }
    }
}
